<template>
    <dict-radio v-model:value="acceptUser.value.type" class="dict-radio" dict-code="pushUser" @change="onChange" />
    <div v-if="isShow" class="box">
        <div class="select">
            <a-tag v-for="(item, index) in acceptUser.value.selects" :key="item.id" closable @close="deleteSelect(index)"> {{ item.name }}</a-tag>
        </div>
        <a-button type="primary" @click="onClick">
            <template #icon><SearchOutlined /></template>
            选择
        </a-button>
        <a-form-item-rest>
            <user-modal ref="userModalRef" @close="selectCallback" />
        </a-form-item-rest>
    </div>
</template>
<script setup>
import { ref, onMounted, reactive, watch, computed } from 'vue'
import { SearchOutlined } from '@ant-design/icons-vue'
import { DictRadio } from '@iframe/tools/components'
import UserModal from './User/Modal'

const props = defineProps({
    value: {
        type: String
    }
})
const userModalRef = ref()
const acceptUser = reactive({
    value: {
        type: null,
        selects: []
    }
})
const emits = defineEmits(['update:value', 'change'])

const isShow = computed(() => {
    return acceptUser.value.type === 2
})
onMounted(() => {
    if (props.value) {
        acceptUser.value = JSON.parse(props.value)
    }
})

watch(
    () => props.value,
    newValue => {
        if (JSON.stringify(acceptUser.value) !== newValue) {
            acceptUser.value = newValue ? JSON.parse(newValue) : {}
        }
    }
)
const onChange = () => {
    acceptUser.value.selects = []
    const json = JSON.stringify(acceptUser.value)
    emits('update:value', json)
    emits('change', json)
}
const onClick = () => {
    userModalRef.value.open(acceptUser.value.selects)
}
const selectCallback = list => {
    if (list && list.length > 0) {
        acceptUser.value.selects = list
    }
    emits('update:value', JSON.stringify(acceptUser.value))
    emits('change', JSON.stringify(acceptUser.value))
}
const deleteSelect = index => {
    acceptUser.value.selects.splice(index, 1)
}
</script>
<style lang="less" scoped>
.dict-radio {
    margin-top: 5px;
}
.box {
    margin-top: 10px;
    display: flex;
    .select {
        flex: 1;
        border: 1px solid #d9d9d9;
        border-radius: 2px;
        transition: border 0.3s, box-shadow 0.3s;
        line-height: 30px;
        :deep(.ant-tag) {
            height: 24px;
            line-height: 22px;
            margin: 0 5px;
        }
    }
    :deep(.ant-btn) {
        width: 92px;
    }
}
</style>
